package cn.zzf.leetcode;

/**
 * <pre>{@code
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 * 如果不存在公共前缀，返回空字符串 ""。
 *
 * 示例 1：
 * 输入：strs = ["flower","flow","flight"]
 * 输出："fl"
 *
 * 示例 2：
 * 输入：strs = ["dog","racecar","car"]
 * 输出：""
 * 解释：输入不存在公共前缀。
 *
 * 提示：
 * 1 <= strs.length <= 200
 * 0 <= strs[i].length <= 200
 * strs[i] 如果非空，则仅由小写英文字母组成
 * }</pre>
 *
 * @author zzf
 * @date 2025-06-04 10:18
 */
public class T0014_LongestCommonPrefix {

    public static String longestCommonPrefix(String[] strs) {
        if(strs.length == 1) return strs[0];
        String str1 = strs[0];
        boolean end = false;
        for (int i = 0; i < str1.length(); i++) {
            char c = str1.charAt(i);
            for (int i1 = 1; i1 < strs.length; i1++) {
                String str = strs[i1];
                if (i >= str.length() || str.charAt(i) != c) {
                    end = true;
                    break;
                }
            }
            if (end) {
                if (i > 0) {
                    return str1.substring(0, i);
                } else {
                    return "";
                }
            }
        }
        return str1;
    }

    public static void main(String[] args) {
        System.out.println(longestCommonPrefix(new String[]{"flower","flower","flower","flower"}));
        System.out.println(longestCommonPrefix(new String[]{"flower", "flow", "flight"}));
        System.out.println(longestCommonPrefix(new String[]{"dog", "racecar", "car"}));
    }

}
